package uk.ac.cam.juliet.zedcat.socialnetworking.plugin;

import java.util.Iterator;
import java.util.LinkedList;

import javax.mail.Message.RecipientType;
import org.codemonkey.vesijama.Email;
import org.codemonkey.vesijama.Mailer;

import uk.ac.cam.juliet.zedcat.db.Account;
import uk.ac.cam.juliet.zedcat.db.EmailRecord;
import uk.ac.cam.juliet.zedcat.socialnetworking.AbstractPlugin;

public class EmailPlugin extends AbstractPlugin {

	private LinkedList<EmailRecord> emailRecords;

	public EmailPlugin(Account acc) {
		super(acc.getAccountID(), acc.getUsername(), acc.getPassword());
		this.emailRecords = acc.getEmailRecords();
	}

	public void pushUpdate(String update) {
		EmailThread t = new EmailThread();
		t.setMessage(update);
		t.start();
	}
	
	public class EmailThread extends Thread {
		String message;
		
		public void setMessage(String message) {
			this.message = message;
		}
		
		public void run() {
			if (emailRecords != null) {
				Iterator<EmailRecord> itr = emailRecords.iterator();

				while (itr.hasNext()) {
					System.out.println("AccountID: " + accountid + " - Type: Email - Sending Email.");
					EmailRecord e = itr.next();
					final Email email = new Email();

					email.setFromAddress("Team Juliet", e.getFromAddress());
					email.setSubject("ZedCat - Update!");
					email.addRecipient("Webcam Subscriber", e.getToAddress(),
							RecipientType.TO);
					email.setText(message);

					new Mailer(e.getSmtpAddress(), e.getSmtpPort(), username,
							password).sendMail(email);
					System.out.println("AccountID: " + accountid + " - Type: Email - Email Sent!");
				}
			} else {
				System.err.println("AccountID: " + accountid + " - Type: Email - No email addresses defined.");
			}
		}
	}
}
